<template>
	<div class="login">
		<div class="container">
			<div class="title">欢迎使用 iVCS 智能视频客服管理系统</div>
			<div class="user_write">
				<el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" class="login_from">
					<el-form-item prop="name">
						<el-input type="name" v-model="loginForm.name" autocomplete="off" placeholder="请输入用户名"></el-input>
						<span class="el-icon-user"></span>
					</el-form-item>
					<el-form-item prop="password">
						<el-input type="password" v-model="loginForm.password" autocomplete="off" placeholder="请输入密码" show-password></el-input>
						<span class="el-icon-key"></span>
					</el-form-item>
					<el-form-item prop="org">
						<el-input v-model="loginForm.org" placeholder="请输入机构名称"></el-input>
						<span class="el-icon-office-building"></span>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="login('ruleForm')" :loading="loadingLogin">登录</el-button>
					</el-form-item>
				</el-form>
			</div>
			<update-pwd v-if="showChangePwd" :showChangePwd="showChangePwd" :isInit="isInit" :isExpired="isExpired" @updatePwd="updatePassword" @closed="showChangePwd = false"></update-pwd>
		</div>
	</div>
</template>

<script>
import { adminlogin, accountLogin, updateAccountInfo } from '@/api/api';
import { jwtDecode } from 'jwt-decode';
import { mapState, mapMutations } from 'vuex';
import { RolePermission, ResourceMap } from '../../utils/permission';
import { removeScreenWatermark } from '@/utils/tool.js';
import UpdatePwd from './UpdatePwd.vue';

export default {
	components: { UpdatePwd },
	mounted() {
		const { params, query } = this.$route;
		console.log(query, 'query');
		if (params && params.key === 'quit') {
			window.location.reload();
		}
		if (query?.code && query?.state) {
			this.initAccountLogin(query.code, query.state);
		}
		if (query.userName && query.password && query.org) {
			this.loginForm.name = query.userName;
			this.loginForm.password = query.password;
			this.loginForm.org = query.org;
			this.login();
		}
		// 清除屏幕水印
		removeScreenWatermark();
	},
	data() {
		let validatename = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('账号不能为空'));
			}
			return callback();
		};
		let validatePass = (rule, value, callback) => {
			if (value === '') {
				return callback(new Error('密码不能为空'));
			}
			return callback();
		};
		let validateOrg = (rule, value, callback) => {
			if (value === '') {
				return callback(new Error('机构不能为空'));
			}
			return callback();
		};
		return {
			isExpired: false,
			showChangePwd: false,
			isInit: false,
			loginForm: {
				name: '',
				password: '',
				org: ''
			},
			// 初始化地址
			urls: {},
			rules: {
				name: [{ validator: validatename, trigger: 'blur' }],
				password: [{ validator: validatePass, trigger: 'blur' }],
				org: [{ validator: validateOrg, trigger: 'blur' }]
			},
			loadingLogin: false // 登录按钮loading加载中，显示隐藏
		};
	},
	computed: {
		...mapState(['urls', 'userInfo'])
	},
	methods: {
		...mapMutations('login', ['SET_LOGIN_USER_INFO', 'SET_LOGIN_URLS']),

		login() {
			this.loadingLogin = true;
			this.loginForm.password = this.loginForm.password.trim();
			this.loginForm.org = this.loginForm.org.trim();
			adminlogin(this.loginForm)
				.then(res => {
					if (res.status === 200) {
						const { data } = res.data;
						console.log('loginResult:', data);
						const jwtToken = jwtDecode(data.accessToken);
						console.log('jwtToken:', jwtToken);
						const urls = data.urls;

						let userInfo = {};
						userInfo.ticket = data.ticket;
						userInfo.org = jwtToken.data.org;
						userInfo.userId = jwtToken.data.id;
						userInfo.name = jwtToken.data.userName;
						userInfo.adminToken = data.accessToken;
						userInfo.role = jwtToken.data.role;
						userInfo.userRole = data.userRole;
						userInfo.loginTime = new Date().getTime();
						userInfo.pwdUpdateDeadline = data.tokenData?.data?.pwdUpdateDeadline; // 密码过期时间 2025-03-03T15:59:59.999Z
						window.uid = userInfo.userId;
						localStorage.setItem('turnserverUrl', urls.turnserverUrl);
						localStorage.setItem('turnserverCredential', urls.turnserverCredential);
						localStorage.setItem('turnserverUsername', urls.turnserverUsername);
						localStorage.setItem(`zco_admin_token_${window.uid}`, data.accessToken);
						localStorage.setItem(`zco_admin_ticket_${window.uid}`, data.ticket);
						localStorage.setItem(`zco_admin_userId_${window.uid}`, userInfo.userId);
						localStorage.setItem(`zco_admin_userName_${window.uid}`, userInfo.name);
						localStorage.setItem(`zco_admin_roleId_${window.uid}`, data.userRole.roleId);
						this.$store.commit('SET_LOGIN_URLS', urls);
						this.$store.commit('SET_LOGIN_USER_INFO', userInfo);
						this.loadingLogin = false;
						if (data.tokenData?.data?.isInitPwd === 'Y') {
							this.showChangePwd = true;
							this.isInit = true;
							return;
						}
						if (data.tokenData?.data?.isExpired === 'Y') {
							this.showChangePwd = true;
							this.isExpired = true;
							return;
						}
						if (data.tokenData?.data?.pwdUpdateDeadline) {
							localStorage.setItem(`zco_admin_pwdUpdateDeadlinee_${window.uid}`, data.tokenData.data.pwdUpdateDeadline);
							localStorage.setItem(`zco_admin_updatePasswordPrompt_${window.uid}`, 'N');
						}
						// get role type
						const permission = this.getRolePermission(data.userRole);
						if (userInfo.role === 'admin') {
							localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(RolePermission['admin']));
							this.$router.push('/index/home'); // 跳转到后管主页
						} else if (userInfo.isRobot) {
							localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(RolePermission['robot']));
							localStorage.setItem('agent_login_time', userInfo.loginTime);
							this.$router.push({ name: 'workbench', params: { data, permission } }); // 跳转到坐席工作台
						} else if (permission.includes('workbench')) {
							localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(permission));
							localStorage.setItem(`zco_route_permission`, JSON.stringify(permission));
							localStorage.setItem(`zco_admin_token`, data.accessToken);
							localStorage.setItem(`zco_admin_ticket`, data.ticket);
							localStorage.setItem(`zco_admin_userId`, userInfo.userId);
							localStorage.setItem('agent_login_time', userInfo.loginTime);
							localStorage.setItem(`agent_user_name`, userInfo.name);
							this.$router.push({ name: 'workbench', params: { data, permission } }); // 跳转到坐席工作台
						} else {
							localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(permission));
							this.$router.push('/index/home'); // 跳转到后管主页
						}
					} else {
						this.$message.error(res.data.message);
						this.loadingLogin = false;
					}
				})
				.catch(err => {
					console.log(err);
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
					this.loadingLogin = false;
				});
		},
		getRolePermission(userRole) {
			if (!userRole || !userRole.roles) {
				return [];
			}
			// 隐藏“账号及权限”菜单，该菜单权限仅给超级管理员；
			const permission = [];
			userRole.roles.map(role => {
				role.permissions.map(item => {
					// eslint-disable-next-line no-extra-parens
					if (![11, 12].includes(item.resourceId) || ([11, 12].includes(item.resourceId) && role.name === 'admin')) {
						permission.push(ResourceMap[item.resourceId]);
					}
				});
			});
			return permission;
		},
		accountLogin() {
			this.$router.push('/account');
		},
		/**
		 * account 免密登录
		 * @param { string } code  query带过来的code
		 * @param { string } state 机构
		 */
		async initAccountLogin(code, state) {
			console.log(code, 'initAccountLogin', state);
			try {
				let params = {
					code: code,
					state: state
				};
				const { data } = await accountLogin(params);
				// console.log(data, 'initAccountLogin  success');
				if (data.code === 200) {
					console.log(data.data, 'tokenData');
					// 需要注意的是此接口多了一层 data
					const jwtToken = jwtDecode(data.data.accessToken);
					// console.log('jwtToken:', jwtToken);
					// console.log(jwtToken.data, 'profile');
					const urls = data.data.urls;
					let userInfo = {};
					userInfo.ticket = data.data.ticket;
					userInfo.org = jwtToken.data.org;
					userInfo.userId = jwtToken.data.id;
					userInfo.name = jwtToken.data.userName;
					userInfo.adminToken = data.data.accessToken;
					userInfo.role = jwtToken.data.role;
					userInfo.isRobot = jwtToken.data.profile.isRobot;
					userInfo.loginTime = new Date().getTime();
					// console.log(userInfo, 'userInfo');
					localStorage.setItem('turnserverUrl', urls.turnserverUrl);
					localStorage.setItem('turnserverCredential', urls.turnserverCredential);
					localStorage.setItem('turnserverUsername', urls.turnserverUsername);
					localStorage.setItem(`zco_admin_token_${window.uid}`, data.data.accessToken);
					localStorage.setItem(`zco_admin_ticket_${window.uid}`, data.data.ticket);
					localStorage.setItem(`zco_admin_userId_${window.uid}`, userInfo.userId);
					this.$store.commit('SET_LOGIN_URLS', urls);
					this.$store.commit('SET_LOGIN_USER_INFO', userInfo);
					// 根据不同的角色登入 管理后台 || 坐席
					const permission = this.getRolePermission(data.data.userRole);
					if (userInfo.role === 'admin') {
						// 跳转到后管主页
						localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(RolePermission['admin']));
						this.$router.push('/index/home');
					} else if (userInfo.isRobot) {
						// 跳转到坐席
						localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(RolePermission['robot']));
						this.$router.push({ name: 'workbench', params: { data: data.data, permission } });
						工作台;
					} else if (permission.includes('workbench')) {
						// 跳转到坐席工作台
						localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(permission));
						localStorage.setItem(`agent_user_name`, userInfo.name);
						this.$router.push({ name: 'workbench', params: { data: data.data, permission } });
					} else {
						// 跳转到后管主页
						localStorage.setItem(`zco_route_permission_${window.uid}`, JSON.stringify(permission));
						this.$router.push('/index/home');
					}
				} else {
					console.log('initAccountLogin function error', data);
				}
			} catch (error) {
				console.log(error);
			}
		},
		updatePassword(value) {
			const params = [{ op: 'replace', path: '/pwd', value: value }];
			const data = {};
			data.params = params;
			let userId = localStorage.getItem(`zco_admin_userId_${window.uid}`);
			data.userId = userId;
			this.$Spin.show();
			updateAccountInfo(data)
				.then(() => {
					this.$Spin.hide();
					this.$message.success('修改密码成功！');
					this.showChangePwd = false;
				})
				.catch(err => {
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		}
	}
};
</script>

<style lang="less">
.login {
	.el-form-item {
		margin-bottom: 22px;
		box-sizing: border-box;
		input {
			background: none;
			border: 1px solid #fff;
			color: #fff;
		}
		.el-input__inner {
			padding: 0 36px;
		}
		input::-webkit-input-placeholder {
			color: #fff;
		}
		input::-moz-input-placeholder {
			color: #fff;
		}
		input::-ms-input-placeholder {
			color: #fff;
		}
	}
}
</style>
<style lang="less" scoped>
.login {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100%;
	background: url('@/assets/img/upload/bg.png') no-repeat;
	background-size: cover;
	background-repeat: no-repeat;
	.container {
		background: rgba(255, 255, 255, 0.5);
		width: 300px;
		min-width: 300px;
		height: 380px;
		max-height: 380px;
		text-align: center;
		border-radius: 10px;
		padding: 30px;
		box-sizing: border-box;
		.el-form-item {
			position: relative;
			span {
				position: absolute;
				left: 10px;
				top: 14px;
				width: 20px;
				color: #fff;
			}
		}
		.login_from {
			padding: 0 24px;
		}
		.title {
			width: 240px;
			height: 68px;
			color: #fff;
			padding: 0 24px 20px 24px;
			line-height: 24px;
			font-size: 14px;
			box-sizing: border-box;
		}
		.el-button {
			width: 100%;
		}
		.user_write {
			margin: 0;
			padding: 0;
		}
	}
}
</style>
